import copy

from ninja import Router
from django.db import transaction

from apps.manager.user_manager.schemas import AddMenuSchema
from apps.manager.user_manager.serializers import MenuSerializer, MenuTreeSerializer
from apps.schemas import R
from models.models import Menu, Api
from utils.auth import ManagerAuthBearer
from utils.decorators import handle_exception

menu_router = Router(tags=["菜单管理"], auth=ManagerAuthBearer())


@menu_router.get("/menu/tree", summary="获取用户全部菜单树")
@handle_exception("获取用户全部菜单树失败")
def get_menus(request):
    menus = Menu.objects.all()
    if not request.user.is_super:
        menus = menus.filter(permissiongroup__user__id=request.user.id, father=None)
    return R.ok(data=MenuTreeSerializer(menus, many=True).data)


@menu_router.get("/menus", summary="获取菜单详情")
@handle_exception("获取菜单详情失败")
def get_menu(request):
    menu = Menu.objects.all()
    return R.ok(data=MenuSerializer(menu, many=True).data)


@menu_router.delete("/menu/{menu_id}", summary="删除菜单")
@handle_exception("删除菜单失败")
def delete_menu(request, menu_id: int):
    if Menu.objects.filter(father_id=menu_id).exists():
        return R.fail(msg="菜单存在子菜单，请先删除子菜单")
    Menu.objects.get(id=menu_id).delete()
    return R.ok(data="删除成功")


@menu_router.post("/menu", summary="添加菜单")
@handle_exception("添加菜单失败")
def add_menu(request, data: AddMenuSchema):
    data_dict = data.dict()
    good_base_data = copy.deepcopy(data_dict)
    del good_base_data["apis"]
    with transaction.atomic():
        menu = Menu.objects.create(**good_base_data)
        menu.apis.set(list(Api.objects.filter(id__in=data_dict.get('apis', []))))
        menu.save()
    return R.ok(data="添加成功")
